package oocl.eshop.service.impl;

import java.io.File;
import java.util.List;

import org.apache.tomcat.util.http.fileupload.FileItem;

import oocl.eshop.dao.FoodDao;
import oocl.eshop.dao.impl.FoodDaoImpl;
import oocl.eshop.po.Food;
import oocl.eshop.po.Merchant;
import oocl.eshop.service.FoodManager;
import oocl.eshop.util.regular.DataMatching;

public class FoodManagerImpl implements FoodManager {
	private FoodDao fooddao = new FoodDaoImpl();

	@Override
	public List<Food> findFoodByName(String foodname) {
		// TODO Auto-generated method stub

		return fooddao.findFoodByName(foodname);
	}

	@Override
	public int updateFood(Food food) {
		// TODO Auto-generated method stub
		return fooddao.updateFood(food);
	}

	@Override
	public int addFood(Food food) {
		// TODO Auto-generated method stub
		return fooddao.AddFood(food);
	}

	@Override
	public int deleteFood(int fId) {
		// TODO Auto-generated method stub
		return fooddao.deleteFood(fId);
	}

	@Override
	public List<Food> findFoodBymid(int mId) {
		// TODO Auto-generated method stub
		return fooddao.findAllFood(mId);
	}

	@Override
	public Food LoadFileFood(List<FileItem> fis, Merchant merchant) {
		int fId = 0;
		String fName = null;
		double fPrice = 0;
		String fViewPath = null;
		for (FileItem fileItem : fis) {
			if (fileItem.isFormField()) {
				System.out.println(fileItem.getFieldName());
				System.out.println(fileItem.getString());
				switch (fileItem.getFieldName()) {
				case "fId":
					fId = Integer.parseInt(fileItem.getString());
					break;
				case "fName":
					fName = fileItem.getString();
					break;
				case "fPrice":
					if (!DataMatching.isPrice(fileItem.getString())) {
						fPrice = -1;
					} else
						fPrice = Double.parseDouble(fileItem.getString());
					break;
				default:
					break;
				}

			} else {
				String fileName = fileItem.getName();
				if (fileName.lastIndexOf(".") == -1) {
					continue;
				}
				fileName = fileName.substring(fileName.lastIndexOf("."));
				System.out.println(fileName);
				try {
					File file = new File("D:/Kinva/" + merchant.getmTel());
					if (!file.exists()) {
						file.mkdirs();
					}
					fViewPath = "http://10.222.232.159/" + merchant.getmTel() + "/" + fName + fPrice + fileName;
					fileItem.write(new File("D:/Kinva/" + merchant.getmTel() + "/" + fName + fPrice + fileName));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		System.out.println("fId=" + fId);
		System.out.println(fName);
		System.out.println(fPrice);
		System.out.println(fViewPath);
		System.out.println(merchant.getmId());
		Food food = new Food(fName, merchant.getmId(), fPrice, fViewPath);
		food.setfId(fId);
		return food;
	}

	@Override
	public Food findFoodByid(int fId) {
		// TODO Auto-generated method stub
		return fooddao.findFoodById(fId);
	}

}
